#!/usr/bin/env bash
set -e

# Parse arguments
for p in "$@"; do
	case "$p" in
		--with-plugins)
			WITH_PLUGINS=true
			shift
			;;
		--with-libs)
			WITH_LIBS=true
			shift
			;;
		-*)
			>&2 echo "Invalid option: $p"
			exit 255
			;;
	esac
done

PROJECT_DIR="$1"
# Check if project path is provided
[[ -z "$PROJECT_DIR" ]] && echo 'Enter path of project to create. Example: ./install-core ./app' && exit 255

# Check if project directory exists
[[ ! -e "$PROJECT_DIR" ]] && echo "Can't find project dir $PROJECT_DIR. Use ./create-app $PROJECT_DIR" && exit 255

kc_dir=$(cd "$(dirname "$0")" && pwd)
core_file=$PROJECT_DIR/app/core.php

cat << 'EOF' > "$core_file"
<?php declare(strict_types=1);
// Copyright (c) 2024 Muvon Un Limited <hello@muvon.io>. All rights reserved.
EOF

echo -e '\e[1;35mInstall kiss core to '"$PROJECT_DIR"'\e[0m'

merge_files() {
	local directory="$1"
	local output_file="$2"

	for file in "$directory"/*; do
		if [ -d "$file" ]; then
			merge_files "$file" "$output_file"
		elif [ -f "$file" ]; then
			echo "Add file $file"

			namespace=$(awk '/^namespace/ {print $2; exit}' "$file" | sed 's/;//')

			if [ -n "$namespace" ]; then
				echo "namespace $namespace {" >> "$output_file"
			else
				echo "namespace {" >> "$output_file"
			fi

			{
				awk '!/^namespace/ && !/^<\?php/ {print}' "$file"
				echo '}'
				echo
			} >> "$output_file"
		fi
	done
}

echo "Write into $core_file"
echo "Merging core"
merge_files "$kc_dir/app/core" "$core_file"

if [[ "$WITH_PLUGINS" == "true" ]]; then
	echo "Merging plugins"
	merge_files "$kc_dir/app/plugin" "$core_file"
fi

if [[ "$WITH_LIBS" == "true" ]]; then
	echo "Merging libs"
	merge_files "$kc_dir/app/lib" "$core_file"
fi

echo '...done'
